#!/usr/bin/env python
# encoding: utf-8
"""
settings.py

Created by Mike Thorpe on 2009-07-25.
Copyright (c) 2009 Mike Thorpe. All rights reserved.
"""

import os
import logging
import urllib

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

from models import Settings

class UserSettings(object):
  """
  This object is an interface to the Settings object 
  in models.
  """
  
  def __init__(self, user=None):
    self.user = user
    if(self.user):
      self.current_settings = self.load_settings()
    
  def load_settings(self):
    """
    Do GQL query for the users Settings object.
    If one doesn't exist, one will be created with 
    default settings.
    """
    query = Settings.all()
    query.filter('user =', self.user)
    
    result = query.get()
    if result:  
      return result
    else:
      # No settings exist for this user.
      # Create new settings object.
      settings = Settings(key_name = "NN_" + self.user.user_id(),
                          user = self.user,
                          email = self.user.email() )
      settings.put()
      return self.load_settings()

  def save_settings(self):
    """
    Save values into data model object.
    """
    
    self.current_settings.put()

  def template_values(self):
    """
    Returns a dictionary to be used by the Django template
    engine.
    """
    if self.current_settings:
      template_values = {
        'email': self.current_settings.email,
        'nickname': self.current_settings.user.nickname(),
        'commonTerms': self.common_terms_to_flags(self.current_settings.commonTerms),
        'includedTerms': map(urllib.quote_plus, self.current_settings.includedTerms),
        'excludedTerms': map(urllib.quote_plus, self.current_settings.excludedTerms)
      }
      return template_values
    else:
      return {}
    
  def common_terms_to_flags(self,terms):
    ## TODO: Convert this whole mess into a boolean list.
    ##
    
    """ 
    Converts the array of common options into a dictionary.
    I hate this function. 
    """
    flags = {'pct_off' : 0, 'wknd_deal' : 0,'sale' : 0 }
    for x in terms:
      if x == "% Off":
        flags['pct_off'] = True
      if x == "Weekend Deal":
        flags['wknd_deal'] = True
      if x == "Sale":
        flags['sale'] = True
        
    return flags

class Welcome(webapp.RequestHandler):
  def get(self):
    user = users.get_current_user()
     
    if user:
      user_settings = UserSettings(user)
      template_values = user_settings.template_values()
      template_values['logout_url'] = users.create_logout_url(self.request.uri)
      
      path = os.path.join(os.path.dirname(__file__), 'views/welcome.html')
      self.response.out.write(template.render(path, template_values))
      
    else:
      self.redirect(users.create_login_url(self.request.uri))
      
class ViewSettings(webapp.RequestHandler):
  def get(self):
    
    user = users.get_current_user()
     
    if user:
      user_settings = UserSettings(user)
      template_values = user_settings.template_values()
      
      path = os.path.join(os.path.dirname(__file__), 'views/settings_view.html')
      self.response.out.write(template.render(path, template_values))
      
    else:
      self.redirect(users.create_login_url(self.request.uri))
    
class UpdateSettings(webapp.RequestHandler):
  """
  CRUD functions for User Settings.
  """
  
  def get(self):
    user = users.get_current_user()
    action = self.request.get('action').lower()
    setting = self.request.get('setting')

    # Update Email
    if action == "update" and setting == "email" and self.request.get('email'):
      user_settings = UserSettings(user)
      
      user_settings.current_settings.email = self.request.get('email')
      user_settings.save_settings()
        
    # Update Common Terms
    if action == "update" and setting == "commonTerms":
      user_settings = UserSettings(user)
      
      user_settings.current_settings.commonTerms = self.request.get_all('common_term')
      user_settings.save_settings()


    ## TODO : Clean up these functions. Be clever and create a shared
    ##        function that takes setting as an argument.
    ##

    # Add new Inlcuded Term
    if action == "add" and setting == "includedTerms":
      new_term = self.request.get('include_term')
    
      if new_term:
        user_settings = UserSettings(user)
        
        if not new_term in user_settings.current_settings.includedTerms:
          user_settings.current_settings.includedTerms.append(new_term)
          user_settings.save_settings()
    
    # Add new Excluded Term
    if action == "add" and setting == "excludedTerms":
      new_term = self.request.get('exclude_term')

      if new_term:
        user_settings = UserSettings(user)

        if not new_term in user_settings.current_settings.excludedTerms:
          user_settings.current_settings.excludedTerms.append(new_term)
          user_settings.save_settings()
      
    # Delete include term
    if action == "delete" and setting == "includedTerms":
      term = self.request.get('term')
  
      if term:
        user_settings = UserSettings(user)
        
        if term in user_settings.current_settings.includedTerms:
          user_settings.current_settings.includedTerms.remove(term)
          user_settings.save_settings()

    # Delete an excludeTerm
    if action == "delete" and setting == "excludedTerms":
      term = self.request.get('term')

      if term:
        user_settings = UserSettings(user)
        
        if term in user_settings.current_settings.excludedTerms:
          user_settings.current_settings.excludedTerms.remove(term)
          user_settings.save_settings()
          
    # reload settings page  
    self.redirect("/")

application = webapp.WSGIApplication(
                                     [
                                     ('/', Welcome),
                                     ('/settings', ViewSettings),
                                     ('/settings/update', UpdateSettings)
                                     ],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
